<template>
	<view class="page">
		<!-- 顶部标题栏 -->
		<view class="header-fixed">
			<view class="header">
				<status-bar></status-bar>
				<view class="header-content">
					<view class="back-btn" @click="goBack">
						<text class="back-icon">←</text>
					</view>
					<view class="title">
						<text>菜谱搜索</text>
					</view>
				</view>
				<!-- 搜索框 -->
				<view class="search-box">
					<input class="search-input" v-model="searchValue" placeholder="请输入菜谱名称" />
					<button class="search-btn" @click="search">搜索</button>
				</view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="content">
	<!-- 精品菜谱 -->
	<view class="vip-section">
		<view class="vip-title">精品名厨视频 - 会员专享</view>
		<scroll-view scroll-x class="vip-list">
			<view class="vip-item" v-for="(item, index) in vipList" :key="index" @click="goToDetail(item)">
				<image :src="item.imagePath" class="vip-img"></image>
				<view class="vip-name">{{ item.name }}</view>
				<view class="vip-badge">VIP</view>
			</view>
		</scroll-view>
	</view>

	<!-- 普通菜谱 -->
	<view class="dish-list">
		<view class="dish-item" v-for="(dish, index) in dishList" :key="index">
			<image :src="dish.imagePath" class="dish-img" @click="goToDetail(dish)"></image>
			<view class="dish-info" @click="goToDetail(dish)">
				<view class="dish-name">{{ dish.name }}</view>
				<view class="dish-tags">{{ dish.tags && dish.tags.length ? dish.tags.join(" / ") : "暂无标签" }}</view>
			</view>
			<view class="dish-action">
				<view class="collect-btn" @click="handleCollect(dish)">
					<text class="collect-icon">{{ dish.isCollected ? '❤️' : '🤍' }}</text>
					<text class="collect-text">{{ dish.isCollected ? '已收藏' : '收藏' }}</text>
				</view>
			</view>
		</view>
	</view>
		</view>
	</view>
</template>

<script setup>
import {
	onLoad,
	onShow
} from "@dcloudio/uni-app";
import {
	ref
} from "vue";
import {
	getDish,
	getVipDish
} from "../../api/searchApi";
import {
	toggleCollection,
	checkCollection
} from "../../api/userApi";
import {
	useUserStore
} from "@/store/user";

	const userStore = useUserStore();
	const id = ref(null);
	const name = ref("");
	const searchValue = ref("");
	const vipList = ref([]);
	const dishList = ref([]);

	onLoad(async (options) => {
		console.log('=== 搜索页 onLoad ===')
		console.log('参数:', options);
		
		// 直接从本地存储读取
		const localToken = uni.getStorageSync('token')
		const localUserInfo = uni.getStorageSync('userInfo')
		console.log('本地 Token:', localToken ? '存在' : '不存在')
		console.log('本地 UserInfo:', localUserInfo ? '存在' : '不存在')
		
		id.value = options.id;
		name.value = options.name;
		searchValue.value = name.value;

		await loadData();
	});

	const loadData = async () => {
		try {
			const vipRes = await getVipDish();
			if (vipRes.code === 200) {
				vipList.value = vipRes.data;
				console.log('vipdish', vipRes.data);
			}

			console.log('正在请求菜品', name.value);
			const dishRes = await getDish({
				currentPage: 1,
				pageSize: 8,
				value: name.value
			});
			console.log('返回结果', dishRes);

			if (dishRes.code === 200) {
				dishList.value = dishRes.data.rows;
				// 如果用户已登录，检查每个菜谱的收藏状态
				if (userStore.token) {
					await checkCollectionStatus();
				}
			}
		} catch (err) {
			console.error("加载失败", err);
		}
	};

	// 搜索按钮点击事件
	const search = async () => {
		name.value = searchValue.value;
		await loadData();
	};

	// 检查收藏状态
	const checkCollectionStatus = async () => {
		if (!userStore.userInfo._id) {
			console.log('用户ID不存在，跳过收藏状态检查')
			return
		}
		
		console.log('检查收藏状态，用户ID:', userStore.userInfo._id)
		
		for (let dish of dishList.value) {
			try {
				const res = await checkCollection(userStore.userInfo._id, dish._id);
				if (res.code === 200) {
					dish.isCollected = res.data;
					console.log(`${dish.name} 收藏状态:`, res.data)
				}
			} catch (err) {
				console.error(`检查 ${dish.name} 收藏状态失败:`, err);
			}
		}
	};

	// 收藏/取消收藏
	const handleCollect = async (dish) => {
		console.log('=== 点击收藏 ===')
		console.log('Token:', userStore.token)
		console.log('UserInfo._id:', userStore.userInfo._id)
		
		// 直接从本地存储读取验证
		const localToken = uni.getStorageSync('token')
		const localUserInfo = uni.getStorageSync('userInfo')
		console.log('本地存储的 token:', localToken)
		console.log('本地存储的 userInfo:', localUserInfo)
		
		// 检查是否登录（优先使用本地存储的 token）
		if (!localToken) {
			console.log('未登录，提示用户登录')
			uni.showModal({
				title: '提示',
				content: '请先登录后再收藏菜谱',
				confirmText: '去登录',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				}
			});
			return;
		}
		
		console.log('已登录，执行收藏操作')
		console.log('用户ID:', userStore.userInfo._id)
		console.log('菜品ID:', dish._id)

		try {
			const res = await toggleCollection(userStore.userInfo._id, dish._id);
			console.log('收藏接口返回:', res)
			
			if (res.code === 200) {
				dish.isCollected = !dish.isCollected;
				uni.showToast({
					title: dish.isCollected ? '收藏成功' : '取消收藏',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res.message || '操作失败',
					icon: 'none'
				});
			}
		} catch (err) {
			console.error("收藏操作失败", err);
			uni.showToast({
				title: '收藏失败，请稍后重试',
				icon: 'none'
			});
		}
	};

	// 跳转到详情页
	const goToDetail = (dish) => {
		// TODO: 跳转到菜谱详情页
		uni.showToast({
			title: `查看 ${dish.name}`,
			icon: 'none'
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack({
			delta: 1
		});
	};
</script>

<style lang="scss">
	.page {
		background-color: #fff;
		min-height: 100vh;
	}

	.header-fixed {
		position: fixed;
		z-index: 9;
		width: 100%;
		top: 0;
		left: 0;
		background-image: url("/static/headerBg.png");
		background-size: 100% 100%;
		padding-bottom: 20rpx;

	.header-content {
		height: 120rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;

		.back-btn {
			position: absolute;
			left: 20rpx;
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.back-icon {
				color: #fff;
				font-size: 48rpx;
				font-weight: bold;
			}
		}

		.title {
			color: #fff;
			font-size: 38rpx;
			font-weight: bold;
		}
	}

		.search-box {
			display: flex;
			align-items: center;
			padding: 0 20rpx;
			margin-top: 10rpx;

			.search-input {
				flex: 1;
				height: 70rpx;
				background: #fff;
				border-radius: 35rpx;
				padding-left: 20rpx;
				font-size: 28rpx;
			}

			.search-btn {
				margin-left: 15rpx;
				background-color: #ff8c00;
				color: #fff;
				font-size: 28rpx;
				border-radius: 35rpx;
				height: 70rpx;
				line-height: 70rpx;
				padding: 0 40rpx;
			}
		}
	}

	.content {
		margin-top: 250rpx;
		padding: 20rpx;
	}

	.vip-section {
		margin-bottom: 40rpx;

		.vip-title {
			font-weight: bold;
			margin-bottom: 20rpx;
			font-size: 30rpx;
			display: flex;
			align-items: center;
			
			&::before {
				content: '';
				width: 6rpx;
				height: 32rpx;
				background: linear-gradient(180deg, #ff9500 0%, #ff6500 100%);
				margin-right: 12rpx;
				border-radius: 3rpx;
			}
		}

		.vip-list {
			display: flex;
			flex-direction: row;
			white-space: nowrap;

			.vip-item {
				display: inline-block;
				margin-right: 20rpx;
				width: 300rpx;
				position: relative;

				.vip-img {
					width: 300rpx;
					height: 200rpx;
					border-radius: 20rpx;
				}

				.vip-name {
					text-align: center;
					margin-top: 10rpx;
					font-size: 28rpx;
				}

				.vip-badge {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					background: linear-gradient(135deg, #ffd700 0%, #ffaa00 100%);
					color: #fff;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					font-size: 22rpx;
					font-weight: bold;
				}
			}
		}
	}

	.dish-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;

		.dish-item {
			display: flex;
			background: #fff;
			border-radius: 20rpx;
			box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
			overflow: hidden;
			position: relative;

			.dish-img {
				width: 200rpx;
				height: 200rpx;
				object-fit: cover;
			}

			.dish-info {
				flex: 1;
				padding: 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.dish-name {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}

				.dish-tags {
					color: #888;
					font-size: 24rpx;
				}
			}

			.dish-action {
				display: flex;
				align-items: center;
				padding-right: 20rpx;

				.collect-btn {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.collect-icon {
						font-size: 44rpx;
					}

					.collect-text {
						font-size: 22rpx;
						color: #666;
						margin-top: 4rpx;
					}
				}
			}
		}
	}
</style>